package net.sky.oa.dao.talkpark.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;
import net.sky.oa.dao.SkyBaseDaoImpl;
import net.sky.oa.dao.talkpark.TalPhotoDao;
import net.sky.oa.model.TalPhoto;
@SuppressWarnings("unchecked")
@Repository
public class TalPhotoDaoImpl extends SkyBaseDaoImpl<TalPhoto> implements TalPhotoDao {
	
	public TalPhotoDaoImpl(){
		super.setPersistType(TalPhoto.class);
	}

	public List<TalPhoto> findAllTalPhoto() {
		String hql="from TalPhoto tp";
		return findByHql(hql);
	}
	
	public  Map  findTalPhotoByAlbumId(final Long albumId,final int currentPage,final int lineSize) throws Exception{
		Map map=new HashMap();
		List list=getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				StringBuffer buffer=new StringBuffer("select new TalPhoto(tp.id,tp.name,tp.picurl,tp.desn) from TalPhoto tp where 1=1 ");
				StringBuffer cbuffer=new StringBuffer("select count(tp.id) from TalPhoto tp where 1=1");
				String hql="";
				if(albumId!=-1){
					hql=" and tp.album.id="+albumId;
					buffer.append(hql);
				    cbuffer.append(hql);
				}
				buffer.append(" order by tp.id asc tp.createtime asc");
				List resultList = new ArrayList();
				 Long count = (long)0;
				 Query query = session.createQuery(buffer.toString());
				 if(currentPage!=-1&&lineSize!=-1) {
			     count =(Long)session.createQuery(cbuffer.toString()).uniqueResult();
			     resultList = query.setFirstResult((currentPage - 1) * lineSize)
					.setMaxResults(lineSize).list();
				 }else {
						resultList = query.list();
					}
				    List list = new ArrayList();
					list.add(count);
					list.add(resultList);				
				    return list;
			}
		});
		      map.put("count",list.get(0) );
              map.put("list", list.get(1) );
                return map;
		
	}

}
